<?php

class packing_list extends ActiveRecord {
/**
 * The followings are the available columns in table 'packing_list':
 * @var integer $id
 * @var integer $shipping_id
 * @var integer $date
 * @var string $subject
 * @var string $ref_no
 * @var string $pod
 */

/**
 * Returns the static model of the specified AR class.
 * @return CActiveRecord the static model class
 */
	CONST REPORT_ID = 1;
    public $shipping_name = '',$pod_name='';
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'packing_list';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
        return array(
            array('date', 'required'),
            array('exported_date', 'numerical', 'integerOnly'=>true),
            array('shipping_line, clearing_agent, handling_agent, notify_party','exist','className'=>'company','attributeName'=>'id'),
            array('subject, pol, pod','length','max'=>120),
            array('attn','length','max'=>50),
            array('ref','unique'),
            array('date','type','type'=>'date','dateFormat'=>'dd/MM/yyyy'),
            array('export_information_id','exist','className'=>'export_information','attributeName'=>'id','on'=>'export'),
        );
    }
	public function beforeValidate() {
        if(is_numeric($this->date))
            $this->date = date('d/m/Y',$this->date);
        return parent::beforeValidate();
    }
	public function beforeSave() {
        if(!is_numeric($this->date)){
        	$_date = explode("/", $this->date);
        	$this->date = mktime(0,0,0,$_date[1],$_date[0],$_date[2]);
        }
        return parent::beforeSave();

    }

    /**
     * @return array relational rules.
     */
    public function relations() {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
        return array(
            'report'=>array(self::HAS_MANY,'packing_list_report','packing_list_id'),
            'packages'=>array(self::HAS_MANY,'packing_list_packages','packing_list_id'),
            'unexportCargoCount'=>array(self::STAT,'cargo','packing_id','condition'=>'cargo.export_information_id = 0'),
            'cargoCount'=>array(self::STAT,'cargo','packing_id'),
            'cargos'=>array(self::HAS_MANY,'cargo','packing_id'),
            'handlingAgent'=>array(self::BELONGS_TO,'company','handling_agent'),
            'clearingAgent'=>array(self::BELONGS_TO,'company','clearing_agent'),
            'notifyParty'=>array(self::BELONGS_TO,'company','notify_party'),
            'shippingLine'=>array(self::BELONGS_TO,'company','shipping_line'),
        );
    }
    /**
     * @return transaction save result
     */
    public function validateCargoInformations() {
        $Ecargo = array(); //Error cargo
        $Fcargo = array(); // Fine cargo
        $returnVal = '';
        if(!$this->isNewRecord) {
            foreach($this->shipment_packages() as $package) {
                foreach($package->cargo() as $c) {
                    if(count($c->packing_details())==0 || count($c->m3())==0 || count($c->qty())==0 || count($c->wt())==0)
                        if(!in_array('#cargo'.$c->id,$Ecargo))
                            $Ecargo[] = "#cargo".$c->id;
                    else
                        if(!in_array('#cargo'.$c->id,$Fcargo))
                            $Fcargo[] = '#cargo'.$c->id;
                }
            }

            $Ecargo = implode($Ecargo,',');
            $Fcargo = implode($Fcargo,',');
            $cs = Yii::app()->getClientScript();
            $s = "$('$Ecargo').button({icons:{primary:'ui-icon-circle-close'}});";
            $s .= "$('$Fcargo').button({icons:{primary:'ui-icon-circle-check'}});";
            $cs->registerScript('cargo#button',$s,CClientScript::POS_READY);
        }
    }
    public function packing_list_report() {
    	$returnVal = array();
    	$returnVal['to'] = $this->detail()->shipping()->cname;
    	$returnVal['item'] = $this->packages();
    	$returnVal['attn'] = $this->detail()->attn;
    	$returnVal['date'] = $this->date;
    	$returnVal['subject'] = $this->subject;
    	return $returnVal;
    }
    public function savePackingList() {
        //Validate models
        $valid = true;
        if(!$this->validate())
            $valid = false;
        foreach($this->packages as $item) {
            if(!empty($item->marking)||!empty($item->pkg)||!empty($item->weight)||!empty($item->height)||!empty($item->width)||!empty($item->length)) {
                if(!$item->validate())
                    $valid = false;
            }
        }
        if(!$valid)
            return false;
        if(!$this->save(false))
            return false;
        foreach($this->packages as $item) {
            if(!empty($item->marking)||!empty($item->pkg)||!empty($item->weight)||!empty($item->height)||!empty($item->width)||!empty($item->length)) {
                $item->packing_list_id = $this->id;
                if(!$item->savePackages())
                    return false;
            }
        }
        return true;
    }
    public function groupPackage(){
    	$packages = $this->packages();
    	$_packages = array();
    	foreach($packages as $package){
    		$_packages[$package->marking][] = $package;
    	}
    	return $_packages;
    }
    /**
     * @return array customized attribute labels (name=>label)
     */
    public function search(){
    	$criteria=new CDbCriteria;
        return new CActiveDataProvider(get_class($this), array(
                'criteria'=>$criteria,
        ));
    }
    public function leftForExport(){
    	$this->exported_date = 0;
    	return $this->search();
    }
        
    public function scopes(){
    	return array(
    		'noexport'=>array(
    			'condition'=>'export_information_id <=0 or export_information_id = NULL',
    		)
    	);
    }
    public function attributeLabels() {
    	return array(
    		'pol'=>'Port of Loading',
    		'pod'=>'Port of Discharge',
    		'date'=>'Date',
    		'shipping_line'=>'Outward carrier',
    		'clearing_agent'=>'Clearing agent',
    		'notify_party'=>'Notify party/Consignee',
    		'handling_agent'=>"Handling agent",
    		'subject'=>'Subject/Topic'    		
    	);
    }
}